<template>
    <div class="crm-project-process-container">
        <el-card shadow="hover">
            <!-- <el-button v-auth="'crm:project:process:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmProjectProcess()">新增</el-button> -->
            <!-- <el-button v-auth="'crm:process:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmProjectProcess()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:process:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-button v-auth="'crm:project:process:assign'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAssignCrmProjectProcess()" :disabled="tableData.selections.length <= 0">指派</el-button>
            <el-table ref="tableCrmProjectProcessRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="过程名称" prop="processName" show-overflow-tooltip></el-table-column>
                <el-table-column label="开始时间" prop="processStartTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="结束时间" prop="processEndTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="完成时间" prop="finishTime" show-overflow-tooltip></el-table-column>
                <el-table-column label="过程状态" prop="processStatus" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.processStatus == '0'" class="color-info">未开始</span>
                        <span v-else-if="scope.row.processStatus == '1'" class="color-primary">进行中</span>
                        <span v-else-if="scope.row.processStatus == '2'" class="color-success">已完成</span>
                        <span v-else class="color-warning">已暂停</span>
                    </template>
                </el-table-column>
                <el-table-column label="执行人" prop="processExecutors" width="220" show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag type="primary" class="mr5" v-for="executor in scope.row?.processExecutors">{{ executor.executorName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:project:process:info', 'crm:project:process:assign', 'crm:project:process:edit', 'crm:project:process:remove', 'crm:project:process:activing', 'crm:project:process:paused', 'crm:project:process:finished']">
                    <template #default="scope">
                        <el-button v-auth="'crm:project:process:info'" type="primary" link @click="onOpenInfoCrmProjectProcess(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:project:process:assign', 'crm:project:process:edit', 'crm:project:process:remove', 'crm:project:process:activing', 'crm:project:process:paused', 'crm:project:process:finished']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:project:process:assign'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenAssignCrmProjectProcess(scope.row)">指派</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:edit'" v-show="['0','1','2','3'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmProjectProcess(scope.row)">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:remove'" v-show="['0','3'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:activing'" v-show="['0','3'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectProcessStatus(scope.row, '1')">启动</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:paused'" v-show="['1'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectProcessStatus(scope.row, '3')">暂停</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:finished'" v-show="['1','3'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectProcessStatus(scope.row, '2')">完成</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:project:process:activing'" v-show="['2'].includes(scope.row.processStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenCrmProjectProcessStatus(scope.row, '1')">重启</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmProjectProcess ref="addCrmProjectProcessRef" @submit="onTableSearch"/>
        <EditCrmProjectProcess ref="editCrmProjectProcessRef" @submit="onTableSearch"/>
        <InfoCrmProjectProcess ref="infoCrmProjectProcessRef"></InfoCrmProjectProcess>
        <AssignCrmProjectProcess ref="assignCrmProjectProcessRef" @submit="onTableSearch"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmProjectProcess from '/@/views/crm/project/process/addCrmProjectProcess.vue';
import EditCrmProjectProcess from '/@/views/crm/project/process/editCrmProjectProcess.vue';
import InfoCrmProjectProcess from '/@/views/crm/project/process/infoCrmProjectProcess.vue';
import AssignCrmProjectProcess from '/@/views/crm/project/process/assignCrmProjectProcess.vue';
import { getCrmProjectProcessList, delCrmProjectProcess, editCrmProjectProcessStatus } from '/@/api/crm/project/process/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/project/process',
    components: { AddCrmProjectProcess, EditCrmProjectProcess, InfoCrmProjectProcess, AssignCrmProjectProcess },
    props: {
        project: {
            type: Object,
            default: {}
        }
    },
    setup(props, { emit }) {
        const tableCrmProjectProcessRef = ref();
        const addCrmProjectProcessRef = ref();
        const editCrmProjectProcessRef = ref();
        const infoCrmProjectProcessRef = ref();
        const assignCrmProjectProcessRef = ref();
        const state = reactive({
            search:{
                projectId: props.project.id || '0',
                processName: undefined,
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'asc',
                pageNum: 1,
                pageSize: 10,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            getCrmProjectProcessList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmProjectProcessRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.processName = undefined;
            state.search.startTime = '';
            state.search.endTime = '';
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmProjectProcess = (row: object) => {
            addCrmProjectProcessRef.value.openDialog({projectId: props.project.id});
        };
        // 打开编辑弹窗
        const onOpenEditCrmProjectProcess = (row: object) => {
            row = row || state.tableData.selections[0];
            row.operate = 'edit';
            editCrmProjectProcessRef.value.openDialog(row);
        };
        // 打开详情弹窗
        const onOpenInfoCrmProjectProcess = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmProjectProcessRef.value.openDialog(row);
        };
        // 打开指派弹窗
        const onOpenAssignCrmProjectProcess = (row?: object) => {
            if(row){
                const projectId = state.search.projectId;
                const processes = [row];
                assignCrmProjectProcessRef.value.openDialog(projectId, processes);
            }else if(state.tableData.selections){
                const projectId = state.search.projectId;
                const processes = state.tableData.selections;
                assignCrmProjectProcessRef.value.openDialog(projectId, processes);
            }
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的过程信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmProjectProcess(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条过程信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmProjectProcess([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        const projectStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '启动',
                '2': '完成',
                '3': '暂停',
            };
            return statusMap[status] || '未知';
        };

        const onOpenCrmProjectProcessStatus = (row: object, status: string) => {
            if('2' == status){
                row.operate = 'finished';
                editCrmProjectProcessRef.value.openDialog(row);
            }else{
                ElMessageBox.confirm(`确认【${ projectStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    editCrmProjectProcessStatus({ id: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 页面加载时
        onMounted(() => {
            loadTableData({});
        });

        watch(() => props.project, (project) => {
            state.search.projectId = project.id || '0';
            loadTableData({});
        },{deep: true})

        return {
            tableCrmProjectProcessRef,
            addCrmProjectProcessRef,
            editCrmProjectProcessRef,
            infoCrmProjectProcessRef,
            assignCrmProjectProcessRef,
            onTableSearch,
            onResetSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmProjectProcess,
            onOpenEditCrmProjectProcess,
            onOpenInfoCrmProjectProcess,
            onOpenAssignCrmProjectProcess,
            onOpenCrmProjectProcessStatus,
            onTabelRowsDel,
            onTabelRowDel,
            ...toRefs(state),
        };
    },
};
</script>